package ru.bmstu.vks.server.view.threads;

import java.util.Date;

import javax.swing.JFrame;

import ru.bmstu.vks.server.view.dialogs.FileTransferingProgressDialog;

public class TransferProgressThread extends Thread {
	private boolean receiving = true;
	private int value = 0;
	private String fileName;
	private long fileSize;
	private int bufferSize;
	private long transferedBytes;
	private double speed;
	private long startTime;
	private long currentTime;

	private JFrame frame;
	
	public TransferProgressThread(String fileName, long fileSize, int bufferSize, long startTime) {
		this.fileName = fileName;
		this.fileSize = fileSize;
		this.bufferSize = bufferSize;
		this.startTime = startTime;
	}
	
	public TransferProgressThread(JFrame frame, String fileName, long fileSize, int bufferSize, long startTime) {
		this(fileName, fileSize, bufferSize, startTime);
		this.frame = frame;
	}
	
	public void run() {
		FileTransferingProgressDialog fileTransfering = new FileTransferingProgressDialog();
		fileTransfering.init(fileName, fileSize, bufferSize);
		if (frame != null) {
			fileTransfering.setLocationRelativeTo(frame);
		}
		fileTransfering.setVisible(true);
		while (receiving) {
			fileTransfering.changeProgress(value, transferedBytes, speed, currentTime - startTime);
		} 
		
		fileTransfering.setMeanSpead(fileSize / (currentTime - startTime));
	}
	
	public void setValue(long transferedBytes) {
		this.value = (int)(((double)transferedBytes/fileSize)*100);
		this.transferedBytes = transferedBytes;
		currentTime = new Date().getTime();
		if (currentTime - startTime != 0) {
			this.speed = transferedBytes / (currentTime - startTime);
		}
	}
	
	public void setReceiving(boolean receiving) {
		this.receiving = receiving;
	}
	
	public double getSpeed() {
		return speed;
	}
}
